package com.netease.examination.util;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * designed by destiny
 *
 * @author destiny
 *         e-mail destinywk@163.com
 *         github https://github.com/DestinyWang
 *         oschina https://git.oschina.net/destinywk
 * @version JDK 1.8.0_101
 * @since 2017/3/30 12:04
 */
public class ExaminationUtil {
    // 全局数组
    private static final String[] strDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    private static final String[] IMAGE_FILE_EXT = {"png", "bmp", "jpg", "jpeg"};

    public static final String LOCAL_IMAGE_DIR = "/Users/destiny/IdeaProjects/toutiao/upload/image/";

    public static final String TOUTIAO_DOMAIN = "http://localhost:8080/";

    public static final String QINIU_DOMAIN = "http://oetw0yrii.bkt.clouddn.com/";

    public ExaminationUtil() {
    }

    // 返回形式为数字跟字符串
    private static String byteToArrayString(byte bByte) {
        int iRet = bByte;
        // System.out.println("iRet="+iRet);
        if (iRet < 0) {
            iRet += 256;
        }
        int iD1 = iRet / 16;
        int iD2 = iRet % 16;
        return strDigits[iD1] + strDigits[iD2];
    }

    // 返回形式只为数字
    private static String byteToNum(byte bByte) {
        int iRet = bByte;
        System.out.println("iRet1=" + iRet);
        if (iRet < 0) {
            iRet += 256;
        }
        return String.valueOf(iRet);
    }

    // 转换字节数组为16进制字串
    private static String byteToString(byte[] bByte) {
        StringBuffer sBuffer = new StringBuffer();
        for (int i = 0; i < bByte.length; i++) {
            sBuffer.append(byteToArrayString(bByte[i]));
        }
        return sBuffer.toString();
    }

    public static String getMD5Code(String strObj) {
        String resultString = null;
        try {
            resultString = new String(strObj);
            MessageDigest md = MessageDigest.getInstance("MD5");
            // md.digest() 该函数返回值为存放哈希值结果的byte数组
            resultString = byteToString(md.digest(strObj.getBytes()));
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return resultString;
    }

    /**
     * 通过UUID获取随机盐值
     *
     * @return  UUID的前6位
     */
    public static String getSalt() {
        return UUID.randomUUID().toString().substring(0, 6);
    }

    /**
     * 判断特定后缀的图片是否允许上传
     *
     * @param fileExt   图片后缀名
     * @return          是否允许上传
     */
    public static boolean isFileAllowed(String fileExt) {
        for (String ext : IMAGE_FILE_EXT) {
            if (ext.equals(fileExt)) {
                return true;
            }
        }
        return false;
    }
}
